// packagBuy/pages/carbuy/carbuy.js
var configUrl = require('../../../config/config'); //引入配置接口文件
var decryptGetPhone = configUrl.decryptGetPhone;
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    CustomBar: app.globalData.CustomBar,
    statusHeight: app.globalData.StatusBar,
    isIPX: app.globalData.isIPX,
    isIPXBottom: app.globalData.isIPXBottom,
    isShowPartnerAll:true,
    showOtherAddr: false,
    isShowMentBtn: true, //管理按钮状态
    selectAlls: false,
    showDeleteBox: false,
    actions: [{
      name: '确定',
      color: '#16BC83',
      type: 'Y'
    }, ],
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.getShippingAddress()
    that.getCarGoodsNumber()
  },
      // 展示合伙人二维码
      partnerCode: function(e) {
        const codeImg = e.target.dataset.url
        wx.previewImage({
          urls: [codeImg],
          current: codeImg // 当前显示图片的http链接
        })
      },
      // 关闭合伙人二维码
      closeCodePop: function() {
        this.setData({
          showPartnerCodePop: false
        })
      },
      // 拨打合伙人电话
      partnerPhone: function() {
        const that = this
        wx.makePhoneCall({
          phoneNumber: that.data.partnerInfo.partnerPhone
        })
      },
     // 展开合伙人信息
     showPartnerAll: function() {
      this.setData({
        isShowPartnerAll:!this.data.isShowPartnerAll
      })
    },
  getShippingAddress() { //获取收货地址
    var that = this;
    var parms = {
      pageFlag: false
    }

    if(that.data.temporaryAddressData){
      let temporaryAddressData = that.data.temporaryAddressData
       var address = temporaryAddressData.province.code + "," + temporaryAddressData.city.code + "," +temporaryAddressData.region.code
       var showaddress = temporaryAddressData.province.name + temporaryAddressData.city.name +temporaryAddressData.region.name
       if (temporaryAddressData.streetName) {
         address += ("," + temporaryAddressData.streetName.code)
         showaddress += (temporaryAddressData.streetName.name)
       }
       that.setData({
         addrPostdata: address,
         showdata: showaddress
       })
    }else{
    // 进入购物车默认为定位地址
    var addrCode = wx.getStorageSync('addrCode')
    var address = addrCode.provinceCode + "," + addrCode.cityCode + "," + addrCode.districtCode + "," + addrCode.townCode
    var showaddress = addrCode.province + addrCode.city + addrCode.district
    that.setData({
      addrPostdata: address,
      showdata: showaddress
    })
    }
   
    var parmsPost = that.data.addrPostdata
    that.getCarGoodsList(parmsPost)

    app.reqFun.requestForm('post', configUrl.addressList, parms, (res) => {
      if (res.data.success == 1) {
          var list = res.data.data.records
          that.setData({
            addressListData: list //收货地址data
          })
      } else {
        wx.showToast({
          title: '查询地址失败：' + res.data.msg,
          icon: 'none'
        })
      }
      console.log(res)
    }, true)
  },
  getCarGoodsList(parms) { // 购物车列表
    var that = this
    var selectCarGoos = wx.getStorageSync('selectCarGoos')
    app.reqFun.requestJson('POST', configUrl.getCarItem, parms, (res) => {
      if (res.data.success == 1) {
        var data = res.data.data
        var allNo = 0 //用于判断是否全选
        var slectNo = 0 //用于判断是否全选
        for (let item of data) {
          for (let val of item.omsCartItemList) {
            if (val.validateErrorStatus == 0 || val.validateErrorStatus == 4) {
              allNo = allNo + 1
            }
            for (var i = selectCarGoos.length - 1; i >= 0; i--) {
              if (val.id == selectCarGoos[i]) {
                if (val.validateErrorStatus == 0 || val.validateErrorStatus == 4) {
                  slectNo = slectNo + 1
                  val.isCheck = true
                } else {
                  selectCarGoos.splice(i, 1)
                }

              }
            }
          }
        }
        if (allNo == slectNo) { //全选
          that.setData({
            selectAlls: true,
          })
        } else {
          that.setData({
            selectAlls: false,
          })
        }
        that.setData({
          carBuy: data,
          allNo: allNo,
          slectNumber:wx.getStorageSync('selectCarGoos').length
        })
        //用于判定限购数和库存
        that.filterStockLimit(data)
        // 计算价格
        that.selectGoodsPrice()
      } else {
        wx.showToast({
          title: '获取购物车列表失败：' + res.data.msg,
          icon: 'none'
        })
      }
    })
  },
  filterStockLimit(data){   //判定限购数和库存
    for(let li of data){
      for(let val of li.omsCartItemList){
        val.addBtn=false   //初始化更改购物车数量按钮
        val.minusBtn=false //初始化更改购物车数量按钮
        if(val.productQuantity==1){  //处理减少按钮
          val.minusBtn=true
        }else{
          val.minusBtn=false
        }
        if(val.limitNum){
          if(val.realStock >= val.limitNum){
            // 当可售库存大于等于限购数
            val.allowNumber = val.limitNum  //给最大选择数赋值
            if(val.limitNum < val.productQuantity  ){
              val.addBtn=true
              val.isCheck=false
              val.msgTitle=`秒杀商品限购${val.limitNum}件`
            }
          }else{ //可售库存小于限购数
            val.allowNumber = val.realStock  //给最大选择数赋值
            if(val.realStock < val.productQuantity){
              val.addBtn=true
              val.isCheck=false
              val.msgTitle=`库存不足最大可购买${val.realStock}件`
            }
          }
        }else{
          val.allowNumber = val.realStock  //给最大选择数赋值
          if(val.realStock < val.productQuantity){
            val.addBtn=true
            val.isCheck=false
            val.msgTitle=`库存不足最大可购买${val.realStock}件`
          }
        }
     }
    }
    var selectCarId=wx.getStorageSync('selectCarGoos')
    var newSelect=[]
    for(let val of data){
      for(let key of val.omsCartItemList){
        for(let id of selectCarId){
          if(key.isCheck && key.id==id){
            newSelect.push(key.id)
          }
        } 
      }
    }
  wx.setStorageSync('selectCarGoos', newSelect)  
   this.setData({
    carBuy:data,
    slectNumber:newSelect.length
   })
   console.log('dataa',data)
  },
  getSkuSpecName(productId) { //获取SPU下可选属性
    var that = this;
    var SelectedSku = JSON.parse(that.data.SelectedSku.skuSpecs)
    app.reqFun.requestJson('get', configUrl.getGoodsSkus + productId, '', (res) => {
      if (res.data.success == 1) {
        var data = res.data.data
        for (let val of SelectedSku) {
          for (let attr of data) {
            for (let ava of attr.specs) {
              if (ava.productAttrItemId == val.value || ava.value == val.value) {
                ava.isCheck = true
              }
            }
          }
        }
        that.setData({
          skuSelectBoxData: data
        })

        that.matchingSku(data)
      }
    }, true)
  },
  selectAttr(e) { //选择属性交互
    var that = this;
    var thisObj = e.currentTarget.dataset.val
    var skuselectData = this.data.skuSelectBoxData //选择框选择值
    for (let val of skuselectData) {
      if (thisObj.attrName == val.key) {
        for (let key of val.specs) {
          if (thisObj.productAttrItemId) {
            if (thisObj.productAttrItemId == key.productAttrItemId && thisObj.productAttributeId == key.productAttributeId) {
              if (key.isCheck) {
                key.isCheck = false
              } else {
                key.isCheck = true
              }
            } else {
              key.isCheck = false
            }
          } else {
            if (thisObj.value == key.value) {
              if (key.isCheck) {
                key.isCheck = false
              } else {
                key.isCheck = true
              }
            } else {
              key.isCheck = false
            }
          }

        }
      }
    }
    that.setData({
      skuSelectBoxData: skuselectData,
    })

    that.matchingSku(skuselectData)
  },
  goGoodsInfo(e) {
    var id = e.currentTarget.dataset.id.productSkuId
    wx.navigateTo({
      url: '../../../packageShop/pages/goodsInfo/goodsInfo?id=' + id,
    })
  },
  matchingSku(skuselectData) { //属性匹配Sku
    var that = this;
    var skus = that.data.skusData //详情返回skulist
    var sceenData = []
    var selectNum = skuselectData.length
    for (let val of skuselectData) {
      for (let val2 of val.specs) {
        if (val2.isCheck) {
          sceenData.push(val2)
        }
      }
    }
    that.setData({
      selectNum: selectNum
    })
    var newSceenData = []
    for (let seSku of sceenData) {
      for (let skO of skus) {
        for (let skv of JSON.parse(skO.skuSpecs)) {
          if (seSku.productAttributeId) {
            if (skv.key == seSku.productAttributeId && skv.value == seSku.productAttrItemId || seSku.value == skv.value) {
              newSceenData.push(skO.id)
            }
          } else {
            if (seSku.value == skv.value) {
              newSceenData.push(skO.id)
            }
          }

        }
      }
    }
    var selectObj = that.getOneSku(newSceenData)
    that.setData({
      thenSlect: selectObj.num
    })
    console.log(selectObj)
    if (selectObj.num == selectNum) {
      for (let sku of skus) {
        if (sku.id == selectObj.skuId) {
          that.setData({
            SelectedSku: sku
          })
        }
      }
    } else if (selectObj == selectNum) {
      for (let sku of skus) {
        if (sku.id == newSceenData[0]) {
          that.setData({
            SelectedSku: sku
          })
        }
      }
    }
  },
  getOneSku(slectNum) { //筛选出已选项匹配的Sku
    if (!slectNum) return false;
    if (slectNum.length === 1) return 1;
    let res = {}
    let maxNum = 0;
    let maxValue = null;
    for (let i = 0; i < slectNum.length; i++) {
      let val = slectNum[i]
      res[val] === undefined ? res[val] = 1 : res[val]++;
      if (res[val] > maxNum) {
        maxNum = res[val];
        maxValue = val
      }
    }
    return {
      skuId: maxValue,
      num: maxNum
    }
  },
  suerThisAttr(e) { //确定更改sku属性规格
    var that = this;
    var parms = {
      id: e.currentTarget.dataset.id,
      productSkuId: e.currentTarget.dataset.val.id
    }
    app.reqFun.requestJson("POST", configUrl.modifyProductAttr, parms, (res) => {
      if (res.data.success == 1) {
        that.onCloseModel()
        var parmsPost = that.data.addrPostdata
        that.getCarGoodsList(parmsPost)
      }
    })
  },
  selectModel(e) { //打开弹窗
    this.getLogin((re)=>{
      if(re){
        var that = this
        if (e.currentTarget.dataset.popup == "buy-Experience") {
          var sku = e.currentTarget.dataset.sku
          var addrCode = that.data.addrPostdata.split(",")
          that.setData({
            carId: sku.id
          })
          var parms = {
            areaCode: addrCode[0],
            skuId: sku.productSkuId
          }
          //请求当前商品的spu和sku集合
          app.reqFun.requestJson('get', configUrl.getGoodsInfoHead, parms, (res) => {
            if (res.data.success == 1) {
              var skus = res.data.data.skus
              that.setData({
                skusData: skus,
                infoData: res.data.data
              })
              for (let val of skus) {
                if (val.id == sku.productSkuId) {
                  console.log(val)
                  that.setData({
                    SelectedSku: val
                  })
                  var spuId = val.productId
                  that.getSkuSpecName(spuId)
                }
                that.setData({
                  modelShowType: e.currentTarget.dataset.val,
                  modelPopup: e.currentTarget.dataset.popup
                })
              }
            }
          })
        } else {
          if (e.currentTarget.dataset.type == 'nowGetCoupon') { //打开领券
            that.getCoupon(e)
            that.setData({
              modelPopup: e.currentTarget.dataset.popup,
              nowGetCouponData: e
            })

          } else if (e.currentTarget.dataset.type == 'nowGetAttr') { //打开选择规格属性
            that.setData({
              modelPopup: e.currentTarget.dataset.popup
            })
          } else {
            that.setData({
              showOtherAddr: false,
              modelPopup: e.currentTarget.dataset.popup
            })
          }
        }
      }
    })
  },
  onCloseModel(e) { //关闭弹窗
    this.setData({
      modelPopup: ''
    })
  },
  slectAddressData(e) { //  选择收货地址列表中的地址
    var that = this
    var data = e.currentTarget.dataset.val
    var datas = this.data.addressListData
    var isHaveAddress
    for (let val of datas) {
      val.defaultStatus = "N"
      val.isChecked = false
      if (val.id == data.id) {
        val.defaultStatus = "Y"
        val.isChecked = true
        wx.setStorageSync('selectAddId', data.id)
        isHaveAddress = val
      }
      this.setData({
        addressListData: datas,
        temporaryAddressData: '',
        isHaveAddress: isHaveAddress,
        modelPopup: '',
      })
      wx.removeStorageSync('temporaryAddressData')

      var addrCode = wx.getStorageSync('addrCode')
      var temporaryAddressData = wx.getStorageSync('temporaryAddressData')
      var isHaveAddr = that.data.isHaveAddress
      if (temporaryAddressData) {
        var address = temporaryAddressData.province.code + "," + temporaryAddressData.city.code + "," + temporaryAddressData.region.code
        var showaddress = temporaryAddressData.province.name + temporaryAddressData.city.name + temporaryAddressData.region.name
        if (temporaryAddressData.streetName) {
          address += ("," + temporaryAddressData.streetName.code)
          showaddress += (temporaryAddressData.streetName.name)
        }
        that.setData({
          addrPostdata: address,
          showdata: showaddress
        })
      } else {
        if (isHaveAddr) {
          var address = isHaveAddr.province + "," + isHaveAddr.city + "," + isHaveAddr.region
          var showaddress = isHaveAddr.provinceName + isHaveAddr.cityName + isHaveAddr.regionName + isHaveAddr.streetName + isHaveAddr.detailAddress
          if (isHaveAddr.street) {
            address += ("," + isHaveAddr.street)
          }
          that.setData({
            addrPostdata: address,
            showdata: showaddress
          })
        } else {
          var address = addrCode.provinceCode + "," + addrCode.cityCode + "," + addrCode.districtCode + "," + addrCode.townCode
          var showaddress = addrCode.province + addrCode.city + addrCode.district
          that.setData({
            addrPostdata: address,
            showdata: showaddress
          })
        }
      }
      var parmsPost = that.data.addrPostdata
      that.getCarGoodsList(parmsPost)
    }
  },
  selectOhterAddr() { //选择其他收货地址
    this.setData({
      showOtherAddr: true,
      sprovince: '',
      scity: '',
      sregion: '',
      sstreetName: ''
    })
    this.getAddressSelectData()
  },
  restSelect(e) { //重新选择
    if (e.currentTarget.dataset.val == 2) {
      this.setData({
        sprovince: '',
        scity: '',
        sregion: '',
        sstreetName: ''
      })
      this.getAddressSelectData()
    } else if (e.currentTarget.dataset.val == 3) {
      this.setData({
        scity: '',
        sregion: '',
        sstreetName: ''
      })
      this.getAddressSelectData(e.currentTarget.dataset.item, true)
    } else if (e.currentTarget.dataset.val == 4) {
      this.setData({
        sregion: '',
        sstreetName: ''
      })
      this.getAddressSelectData(e.currentTarget.dataset.item, true)
    }
  },
  getAddressSelectData(e, aa) { //查询4级地址数据
    var that = this;
    var parms = {
      parentCode: 100000000000
    }
    var data = ""
    if (e) {
      if (aa) {
        data = e
      } else {
        data = e.currentTarget.dataset.val
      }
      console.log(data)
      parms.parentCode = data.code
      if (data.areaLevel == 2) {
        that.setData({
          sprovince: data
        })
      } else if (data.areaLevel == 3) {
        that.setData({
          scity: data
        })
      } else if (data.areaLevel == 4) {
        that.setData({
          sregion: data
        })
      } else if (data.areaLevel == 5) {
        that.setData({
          sstreetName: data
        })
      }
    }
    app.reqFun.requestJson('get', configUrl.listByParentCode, parms, (res) => {
      if (res.data.success == 1) {
        if (res.data.data.length > 0) {
          that.setData({
            itemsAddr: res.data.data,
          })
        } else {
          that.setData({ //关闭弹窗
            modelPopup: '',
            showOtherAddr: false
          })
          var temporaryAddressData = {}
          temporaryAddressData.province = that.data.sprovince
          temporaryAddressData.city = that.data.scity
          temporaryAddressData.region = that.data.sregion
          temporaryAddressData.streetName = that.data.sstreetName
          wx.setStorageSync('temporaryAddressData', temporaryAddressData)
          wx.removeStorageSync('selectAddId')
          that.setData({
            temporaryAddressData: temporaryAddressData
          })
          that.getShippingAddress()

        }
      } else {
        wx.showToast({
          title: '查询地址失败：' + res.data.msg,
          icon: 'none'
        })
      }
    }, true)
  },
  // 查询优惠券   
  getCoupon(data) {
    var that = this;
    var thisdata = data.currentTarget.dataset.thisdata
    var newArrs = []
    console.log(thisdata)
    for (let val of thisdata) {
      newArrs.push(val.productId)
    }
    var strAr = Array.from(new Set(newArrs))

    var parms = {
      paramsRaw: strAr.join(",")
    }
    app.reqFun.requestForm('POST', configUrl.shoppingCartCoupons, parms, (res) => {
      if (res.data.success == 1) {
        if (res.data.data) {
          that.setData({
            couponListData: res.data.data.records
          })
        } else {
          that.setData({
            couponListData: []
          })
        }

      } else {
        wx.showToast({
          title: '获取优惠失败：' + res.data.msg,

        })
      }
    })
  },
  receiveCoupon(e) { //领券
    var that = this;
    var parms = {
      couponId: e.currentTarget.dataset.item.id,
      receivePage: 0,
      receivePlatform: 'mini'
    }
    app.reqFun.requestJson('POST', configUrl.receiveCoupon, parms, (res) => {
      if (res.data.success == 1) {
        wx.showToast({
          title: '领取优惠券成功',
        })
        that.getCoupon(that.data.nowGetCouponData)
      } else {
        wx.showToast({
          title: '领取优惠券失败',
          icon: "none"
        })
      }
    })
  },
  changeGoodsNum(e) { //修改商品数量
    var that = this;
    var number = e.detail
    if(number){
      if(number>0){
        var goods = e.currentTarget.dataset.val
        var parms = {
          productSkuId: goods.productSkuId,
          quantity: number,
          id: goods.id
        }
        app.reqFun.requestJson("POST", configUrl.modifyQuantity, parms, (res) => {
          var addrPostdata = that.data.addrPostdata
          that.getCarGoodsList(addrPostdata)
        }, true)
      }else{
        wx.showToast({
          title: '请正确填写商品数量。',
          icon:'none',
          duration:2500
        })
      }
      
    }
   
  },
  goshopping(){ //去购物
    wx.reLaunch({
      url: '/pages/newIndex/newIndex'
    })
  },
  deleteShowBox(e) { //删除验证弹窗
    var arr = this.data.deleteCarGoods
    if (arr.length == 0) {
      wx.showToast({
        title: '请选择删除的商品',
        icon: 'none'
      })
    } else {
      this.setData({
        showDeleteBox: true
      })
    }

  },
  onClose() { //关闭删除弹窗
    this.setData({
      showDeleteBox: false
    });
  },
  deleteCarGoods(e) { //删除购物车商品-批量

    var that = this;
    var parms = ''
    wx.showModal({
      title: '确认删除当前商品吗?',
      success(res) {
        if (res.confirm) {
          if (e.currentTarget.dataset.one == 1) {
            const {
              instance
            } = e.detail;
            instance.close();
            parms = [e.currentTarget.dataset.val.id]
          } else {
            parms = that.data.deleteCarGoods
          }
          that.deleteGoodsPost(parms)
        }
      }
    })
  },
  deleteGoodsPost(parms) { //删除购物车商品 请求
    var that = this;
    console.log(parms)
    var ids = wx.getStorageSync('selectCarGoos')
    app.reqFun.requestJson("POST", configUrl.deleteCarGoods, parms, (res) => {
      if (res.data.success == 1) {
        var addrPostdata = that.data.addrPostdata
        that.getCarGoodsList(addrPostdata)
        that.getCarGoodsNumber()
        if (ids.length > 0) {
          for (var i = ids.length - 1; i >= 0; i--) {
            for (let did of parms) {
              if (ids[i] == did) {
                ids.splice(i, 1)
              }
            }

            wx.setStorageSync('selectCarGoos', ids)
          }
        } else {
          wx.setStorageSync('selectCarGoos', ids)
        }

      }
    }, true)
  },
  //单选购物车商品
  selectOneGoods(e) {
    if (this.data.isShowMentBtn) {
      var that = this;
      var id = e.currentTarget.dataset.val.id
      var carBuy = this.data.carBuy
      for (let item of carBuy) {
        for (let val of item.omsCartItemList) {
          if (val.id == id) {
            if (val.isCheck) {
              val.isCheck = false
            } else {
              val.isCheck = true
            }
          }
        }
      }
      var slectArr = []
      var slectNo = 0
      var oldNo = 0
      for (let item of carBuy) {
        for (let val of item.omsCartItemList) {
          oldNo = oldNo + 1
          if (val.isCheck) {
            slectArr.push(val.id)
            slectNo = slectNo + 1
          }
          if (val.validateErrorStatus == 0) {

          }
        }
      }
      if (slectNo == oldNo) {
        that.setData({
          selectAlls: true
        })
      } else {
        that.setData({
          selectAlls: false
        })
      }
      that.setData({
        carBuy: carBuy,
        slectNumber: slectNo
      })
      wx.setStorageSync('selectCarGoos', slectArr)
      this.selectGoodsPrice()
    } else {
      var that = this;
      var id = e.currentTarget.dataset.val.id
      var carBuy = this.data.carBuy
      for (let item of carBuy) {
        for (let val of item.omsCartItemList) {
          if (val.id == id) {
            if (val.deleteisCheck) {
              val.deleteisCheck = false
            } else {
              val.deleteisCheck = true
            }
          }
        }
      }
      var slectArr = []
      var slectNo = 0
      var oldNo = 0
      for (let item of carBuy) {
        for (let val of item.omsCartItemList) {
          oldNo = oldNo + 1
          if (val.deleteisCheck) {
            slectArr.push(val.id)
            slectNo = slectNo + 1
          }
          if (val.validateErrorStatus == 0) {

          }
        }
      }
      if (slectNo == oldNo) {
        that.setData({
          selectAllsTwo: true
        })
      } else {
        that.setData({
          selectAllsTwo: false
        })
      }
      that.setData({
        carBuy: carBuy
      })
    }
    that.setData({
      deleteCarGoods: slectArr
    })
  },
  //全选购物车商品
  selectAllGoods(e) {
    var that = this;
    if (this.data.isShowMentBtn) { //正常操作购物车
      var carBuy = this.data.carBuy
      for (let item of carBuy) {
        for (let val of item.omsCartItemList) {
          if (e.currentTarget.dataset.val) {
            val.isCheck = false
            this.setData({
              selectAlls: false,
              carBuy: carBuy
            })
          } else {
            if (val.validateErrorStatus == 0 || val.validateErrorStatus == 4) {
              val.isCheck = true
            }

            this.setData({
              selectAlls: true,
              carBuy: carBuy
            })
          }
        }
      }
      var slectArr = []
      for (let item of carBuy) {
        for (let val of item.omsCartItemList) {
          if (val.isCheck) {
            slectArr.push(val.id)
          }
          that.setData({
            slectNumber: slectArr.length
          })
        }
      }

      this.selectGoodsPrice()
      wx.setStorageSync('selectCarGoos', slectArr)
    } else { //管理-删除购物车商品
      var carBuy = this.data.carBuy
      for (let item of carBuy) {
        for (let val of item.omsCartItemList) {
          if (e.currentTarget.dataset.val) {
            val.deleteisCheck = false
            this.setData({
              selectAllsTwo: false,
              carBuy: carBuy
            })
          } else {
            val.deleteisCheck = true
            this.setData({
              selectAllsTwo: true,
              carBuy: carBuy
            })
          }
        }
      }
      var slectArr = []
      for (let item of carBuy) {
        for (let val of item.omsCartItemList) {
          if (val.deleteisCheck) {
            slectArr.push(val.id)
          }
        }
      }
      that.setData({
        deleteCarGoods: slectArr
      })
    }

  },
  // 计算购物车商品价格
  selectGoodsPrice() {
    var carBuy = this.data.carBuy
    var allPrice = 0
    var number = 0
    var seNumber = 0
    for (let item of carBuy) {
      for (let val of item.omsCartItemList) {
        if (val.isCheck) {
          seNumber = seNumber + 1
          if (val.promotionPrice) {
            allPrice = allPrice + (val.promotionPrice*val.productQuantity)
          } else {
            allPrice = allPrice + val.totalPrice
          }
          if (val.realStock == 0) {
            number = number + 1
          }
        }
      }
    }
    if (number == seNumber) {
      this.setData({
        subReturnDis: false
      })
    } else {
      this.setData({
        subReturnDis: true
      })
    }
    this.setData({
      allPrice: allPrice.toFixed(2)
    })
  },
  changeBtn() { //  切换管理功能按钮状态
    if (this.data.isShowMentBtn) {
      this.setData({
        isShowMentBtn: false
      })

    } else {
      this.setData({
        isShowMentBtn: true
      })

    }
  },
  goSearchCoupon(e) { //优惠券跳转
    var info = e.currentTarget.dataset.item
    wx.navigateTo({
      url: `../../../packageShop/pages/shopSearch/shopSearch?couponId=${info.id}&from=coupon`,
    })
  },
  getCarGoodsNumber() { //查询购物车商品数-
    var that = this;
    app.reqFun.requestJson('POST', configUrl.getCarNumber, '', (res) => {
      if (res.data.success == 1) {
        that.setData({
          carGoods: res.data.data
        })
      }
    }, true)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    setTimeout(()=>{
      this.setData({
        partnerInfo:getApp().globalData.partnerInfo
      })
      },500)
    this.onLoad()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onLoad()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },
  goreBack: function (e) {
    wx.navigateBack({
      delta: 1
    })
  },
  selectNum() {
    console.log("")
  },
  goClassify(e) { //进入分类
    wx.reLaunch({
      url: '/pages/classify/classify',
    })
  },
  goConfirmOrder(e) { //下单去确认订单页
    this.getLogin((re)=>{
      if(re){
        var skus = []
        var shopGoods = this.data.carBuy
        for (let val of shopGoods) {
          for (let sku of val.omsCartItemList) {
            if (sku.isCheck) {
              skus.push({
                skuId: sku.productSkuId,
                number: sku.productQuantity
              })
              if (sku.validateErrorStatus == 1 || sku.validateErrorStatus == 3 || sku.validateErrorStatus == 2) {
                wx.showToast({
                  title: '已选择商品' + sku.validateErrorMessage,
                  icon: 'none'
                })
                return;
              }
            }
          }
        }
        if (skus.length == 0) {
          wx.showToast({
            title: '请选择需下单结算的商品',
            icon: 'none'
          })
          return;
        }
        var submitdata = {
          sku: skus
        }
        submitdata.omsOrderType = 'REGULAR',
          submitdata.settlementMethod = "SHOPPING_CART"
        wx.setStorageSync('submitSku', submitdata)
        wx.navigateTo({
          url: '/packagBuy/pages/confirmOrder/confirmOrder?type=orderOnline&buyLine=car',
        })
      }
    })
  },
  getLogin(callback){   //登录调用 - 弹出登录窗
    var that=this;
    wx.getSetting({
      success: (res) => {
      var statu = res.authSetting;
      if (!statu['scope.userLocation']) { //没授权
        that.setData({
          'showSetting':true,
          'getSetting':true
        })
        callback(false)
      }else{
        if(!wx.getStorageSync('loginMsg').loginState){
          if (wx.getUserProfile) {
            app.getUserProfile(function(){
              console.log('登录 成功')
              that.setData({
                getPhoneNumberData:{
                  isShowGetPhoneNumber:true
                }
              })
            })
          } else {
            if(!wx.getStorageSync('loginMsg').bindingPhone){
              that.setData({
                getPhoneNumberData:{
                  isShowGetPhoneNumber:true
                }
              })
            } else {
              callback(true)  //低版本微信绑过电话视为已登录
            }
          }
          // this.setData({
          //   isShowGetUserInfo:true
          // })
          callback(false)   //需要登录
        }else{
          callback(true)  //已登录
        }
      }
    }
  })
  },
  /**绑定手机号 ---start*/
  closeGetphone(){
    this.setData({
      getPhoneNumberData:{
        isShowGetPhoneNumber:false
      }
    })
  },
  getPhoneNumber(e){
    let loginMsg = wx.getStorageSync('loginMsg')
    if (e.detail.iv && e.detail.encryptedData) {
      let option = {}
      option.encryptedData = e.detail.encryptedData
      option.iv = e.detail.iv
      option.openid = loginMsg.openid
      option.session_key = loginMsg.session_key
      app.reqFun.requestJson('POST',decryptGetPhone,option,(res)=>{
        if(res.data.success==1){
          loginMsg.bindingPhone = true
          wx.setStorageSync('loginMsg', loginMsg)
          this.setData({
            getPhoneNumberData:{
              isShowGetPhoneNumber:false
            }
          })
          wx.showToast({
            title: '绑定成功。',
          })
        }
      })
    } else {
      console.log('取消')
    }
  },
  /**  绑定手机号 ---end*/
})